package baiqitun.stupro.security.core.config;

import baiqitun.stupro.common.constant.SysConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

import java.util.Arrays;

/**
 * @author kedaji
 */
@EnableAuthorizationServer
@Configuration
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisConnectionFactory redisConnectionFactory;
    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        // 使用令牌增强器链将Spring Security OAuth2的令牌逐步增强为Jwt令牌
        TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
        // 向令牌增强器链上添加令牌增强器
        tokenEnhancerChain.setTokenEnhancers(Arrays.asList(tokenEnhancer(), accessTokenConverter()));

        endpoints
                .authenticationManager(authenticationManager)
                .tokenStore(redisTokenStore())
                .tokenEnhancer(tokenEnhancerChain)
                .userDetailsService(userDetailsService);
    }

    @Bean
    public RedisTokenStore redisTokenStore(){
        return new RedisTokenStore(redisConnectionFactory);
    }

    @Bean
    public TokenEnhancer tokenEnhancer(){
        return new JwtAccessTokenConverter();
    }


    @Bean
    public JwtAccessTokenConverter accessTokenConverter() {
        // Jwt令牌转换器
        JwtAccessTokenConverter accessTokenConverter = new JwtAccessTokenConverter();
        // 为令牌添加签名
        accessTokenConverter.setSigningKey(SysConstant.PRIVATE_KEY);
        return accessTokenConverter;
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security
                // 只有认证的用户才能访问check_token的url对token进行校验
                .checkTokenAccess("isAuthenticated()")
                .allowFormAuthenticationForClients();
    }

        @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        // 认证服务器作为客户端进行认证
        clients.inMemory().withClient("stupro")
                .secret("$2a$10$ryMJZ1xb4Hd68zFRh16evustEhI9YdWpzCNUiNO29Mn91KRcKTeyO").authorizedGrantTypes("password", "refresh_token")
                // 访问令牌有效时间
                .accessTokenValiditySeconds(7200)
                // 刷新令牌有效时间
                .refreshTokenValiditySeconds(2592000)
                .scopes("all");

    }
}
